//
//  YTHomeViewModel.m
//  yitaicaijing
//
//  Created by DIANGHONG on 2018/7/13.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "YTHomeViewModel.h"


@interface YTHomeViewModel ()

@property(nonatomic ,assign)int page; // 当前页

@end
@implementation YTHomeViewModel

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.page = 1;
    }
    return self;
}

- (NSMutableDictionary *)dict
{
    if (!_dict) {
        _dict = [NSMutableDictionary dictionaryWithCapacity:5];
    }
    return _dict;
}



// 加载banner
- (void)loadBannerWithCompletion:(void(^)(BOOL isSucc, NSString *error))completion
{
    [YTNetworkManager.shareManager requestBannerWithCompletion:^(YTHomeBanner *banner, BOOL isSuccess, NSString *error)
    {
        if (!isSuccess) {
            // 加载失败
            completion(false,error);
            return ;
        }
        
        self.banner = banner;
        completion(isSuccess,nil);
    }];
}

// 加载快讯列表
- (void)loadNewFlashCompletion:(void(^)(BOOL isSucc, NSString *error))completion
{
    [YTNetworkManager.shareManager requestNewFlashWithCompletion:^(NSArray *list, BOOL isSuccess, NSString *error)
    {
        // 请求失败
        if (!isSuccess) {
            completion(false,error);
            return ;
        }
        
        self.flashList = list;
        
        completion(isSuccess,nil);
    }];
}

// 加载首页列表
- (void)loadHomeListWithTerm_id:(NSString *)term_id
                         pullup:(BOOL)pullup
                       completion:(void(^)(BOOL isSucc, NSString *error))completion
{
        
    if (pullup) {
        self.page++;
        NSLog(@"%zd",self.model.list.count);
        if (self.model.list.count == [(YTHomeMainModel *)self.dict[term_id] total].intValue) {
            completion(YES,@"没数据");
            return;
        }
    }else{
        self.page = 1;
    }
    
    if (self.cateList.firstObject.term_id == term_id) {
    // 加载banner
    [self loadBannerWithCompletion:^(BOOL isSucc, NSString *error) {
        if (!isSucc) {
            completion(false,error);
            return ;
        }
        
        // 加载快讯列表
        [self loadNewFlashCompletion:^(BOOL isSucc, NSString *error) {
            
            if (!isSucc) {
                completion(false,error);
                return ;
            }
            
            [YTNetworkManager.shareManager requestHomeListWithTerm_id:term_id
                                                                paged:self.page
                                                            page_size:10
                                                            menu_order:!pullup
                                                              mintime:pullup ? self.model.list.lastObject.post_date : nil
                                                           completion:^(YTHomeMainModel *model, BOOL isSuccess, NSString *error)
             {
                 if (!isSucc) {
                     completion(false,error);
                     return ;
                 }
                 
                 // 下拉刷新
                 if (!pullup) {
                     self.model = model;
                     
                     self.dict[term_id] = model;
                 }else{
                     
                     self.model.list = [self.model.list arrayByAddingObjectsFromArray:model.list];
                    // [self.dict[term_id] setList:[[self.dict[term_id] list] arrayByAddingObjectsFromArray:model.list]];
                 }
                 
                
                 
                 completion(YES,nil);
                 
             }];
        
            
        }];
    }];
        
    }else{
        
        
        [YTNetworkManager.shareManager requestHomeListWithTerm_id:term_id
                                                            paged:self.model.page.intValue
                                                        page_size:10
                                                        menu_order:!pullup
                                                        mintime:pullup ? self.model.list.lastObject.post_date : nil
                                                       completion:^(YTHomeMainModel *model, BOOL isSuccess, NSString *error) {
            
            if (!isSuccess) {
                completion(false,error);
                return ;
            }
            
            // 下拉刷新
            if (!pullup) {
                self.model = model;
                
                self.dict[term_id] = model;
            }else{
                
                self.model.list = [self.model.list arrayByAddingObjectsFromArray:model.list];
               // [self.dict[term_id] setList:[[self.dict[term_id] list] arrayByAddingObjectsFromArray:model.list]];

            }
            
            completion(YES,nil);
        }];
    }

        
}

// 请求首页分类
- (void)loadCateListWithCompletion:(void(^)(BOOL isSucc, NSString *error))completion
{
    
    if (!YTNetworkManager.shareManager.account.accessToken) {

        CFUUIDRef cfuuid = CFUUIDCreate(kCFAllocatorDefault);
        NSString *device_id = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, cfuuid));
        NSString *rand_str = [NSString return16LetterAndNumber];
        NSString *timestamp = [self currentTimeStr];
        
        NSString *signature = [self signatureWithDevice_id:device_id rand_str:rand_str timestamp:timestamp];
        
        // 获取aceessToken
        [YTNetworkManager.shareManager requestAccessWithSignature:signature
                                                        device_id:device_id
                                                         rand_str:rand_str
                                                        timestamp:timestamp
                                                       completion:^(BOOL isSucc, NSString *error)
         {
             if (!isSucc) {
                 completion(false ,error);
                 return ;
             }
             // 获取分类列表
             [YTNetworkManager.shareManager requestCatorgListWithCompletion:^(NSArray *list, BOOL isSuccess, NSString *error)
              {
                  // 请求失败
                  if (!isSuccess) {
                      completion(false ,error);
                      return ;
                  }
                  self.cateList = list;
//                  completion(isSuccess,nil);
                // 获取分类热搜列表
                  [YTNetworkManager.shareManager requestHotSearchWithCompletion:^(NSArray *list, BOOL isSucc, NSString *error)
                  {

//                      if (!isSucc) {
//                          completion(false,@"网络不给力...");
//                          return ;
//                      }
                      
                      if (YTNetworkManager.shareManager.account.auth)
                      {
                          [YTNetworkManager.shareManager requestUserIsSiginWithCompletion:^(BOOL isSucc, BOOL isSign)
                           {
                               if (!isSucc) {
                                   // 什么都不做
                               }
                               YTNetworkManager.shareManager.account.isSign = [NSNumber numberWithBool:isSign];
                           }];
                      }
                      self.hotSearchList = list;
                      completion(YES,nil);
                  }];

              }];
        }];
    }else{
    
    [YTNetworkManager.shareManager requestCatorgListWithCompletion:^(NSArray *list, BOOL isSuccess, NSString *error)
    {
        // 请求失败
        if (!isSuccess) {
            completion(false ,error);
            return ;
        }
        self.cateList = list;
        
        [YTNetworkManager.shareManager requestHotSearchWithCompletion:^(NSArray *list, BOOL isSucc, NSString *error) {
            
            if (!isSucc) {
                completion(false,@"网络不给力...");
                return ;
            }
            
            self.hotSearchList = list;
             completion(isSuccess,nil);
        }];
        
    }];
        
    }
}
//获取当前时间戳
- (NSString *)currentTimeStr
{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

// 加签名的方法
- (NSString *)signatureWithDevice_id:(NSString *)device_id
                            rand_str:(NSString *)rand_str
                           timestamp:(NSString *)timestamp
{
    NSString *signatureStr = [NSString stringWithFormat:@"app_id=%@&app_secret=%@&device_id=%@&rand_str=%@&timestamp=%@",kApp_ID,kApp_Secret,device_id,rand_str,timestamp];
    

    return [signatureStr md5];
}

@end
